package com.safeneeds.linguimana.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;



import java.text.SimpleDateFormat;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.safeneeds.linguimana.entity.PortGlutLog;
import com.safeneeds.linguimana.entity.dao.IPortGlutLogDao;
import com.safeneeds.linguimana.ser.IBgLogService;

/**
 * 拦截器   用来记录使用者  访问网站的浏览记录
 * Servlet Filter implementation class PortURLRecordFilter
 */
public class PortURLRecordFilter implements Filter {

	/* 运行模式(测试:false 上线:true) */
	private boolean runMode;
    /**
     * Default constructor. 
     */
    public PortURLRecordFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 获取用户浏览网页地址或操作后台系统记录
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		if(runMode){
			//过滤    获取用户浏览网页地址或操作后台系统记录
			HttpServletRequest hreq = (HttpServletRequest) request;
			PortGlutLog glutLog = new PortGlutLog();
			glutLog.setRequestUrl(hreq.getRequestURI());
			glutLog.setIp(hreq.getLocalAddr());
			glutLog.setTime(new java.util.Date());
			ApplicationContext ac = WebApplicationContextUtils
			.getRequiredWebApplicationContext(((HttpServletRequest) request).getSession()
					.getServletContext());// spring容器
			IPortGlutLogDao glutLogDao = (IPortGlutLogDao) ac.getBean("portGlutLogDao");
			glutLogDao.insertLog(glutLog);
		}
		
		
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * 
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		//获取参数
		String runmodeFg = fConfig.getInitParameter("runMode");
		if("false".equals(runmodeFg)){
			//测试开发模式
			runMode = false;
		}else{
			//运行模式
			runMode = true;
		}
	}

}
